package com.elecbook.auth.service;

import com.elecbook.auth.model.po.LoginsUserDetail;
import com.elecbook.auth.model.po.Role;
import com.elecbook.auth.model.po.User;
import com.elecbook.auth.mapper.RoleMapper;
import com.elecbook.auth.mapper.RolePermissionMapper;
import com.elecbook.auth.mapper.UserPermissionMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public abstract class AbstractAuthService implements AuthService {

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserPermissionMapper userPermissionMapper;

    /**
     * description 其他实现类从抽象类来获取的抽象方法，根据user实体获取所有的用户信息，包括权限信息
     *
     * @author zken
     * CreateDate 2024/11/2 22:15:56
     */
    public UserDetails loadUserByUserPo(User user) throws UsernameNotFoundException {

        // 以此开始，从user进行获取数据内容
        LoginsUserDetail loginsUserDetail = new LoginsUserDetail(user);

        // 获取角色名称
        List<Role> roles = roleMapper.findRoleIdListByUserId(user.getId());

        // 如果角色为空，则什么权限都不添加，包括最细粒度的权限
        if (roles != null && !roles.isEmpty()) {
            List<Integer> roleIds = roles
                    .stream()
                    .map(Role::getId)
                    .collect(Collectors.toList());
            List<String> roleNames = roles
                    .stream()
                    .map(Role::getName)
                    .collect(Collectors.toList());
            // 获取角色对应的所有权限列表
            List<String> rolePermissionNameList = rolePermissionMapper.selectRolePermissionListByRoleId(roleIds);
            // 用户权限的集合
            Set<String> userPermissionNameSet = new HashSet<>(rolePermissionNameList);

            // 获取用户独有的权限列表
            List<String> userOnlyPermissionNameList = userPermissionMapper.selectPermissionByUserId(user.getId());
            userPermissionNameSet.addAll(userOnlyPermissionNameList);
            // 用户所拥有的所有权限的列表 -- 根据集合创建（目的：消除重复的权限名称）
            List<String> userPermissionNameList = new ArrayList<>(userPermissionNameSet);


            // 添加对应的权限内容
            loginsUserDetail.setPermissionNames(userPermissionNameList);
            loginsUserDetail.setRoleNames(roleNames);
        }
        return loginsUserDetail;
    }
}
